package com.syj.jsxjj.ui.discover;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.syj.jsxjj.events.UIBaseEvent;
import com.syj.jsxjj.ui.my.activity.ForgetPayPwdActivity;
import com.syj.jsxjj.util.SpUtil;
import com.syj.jsxjj.util.Tool;
import com.syj.jsxjj.util.ViewUtil;
import com.syj.jsxjj.R;
import com.syj.jsxjj.app.App;
import com.syj.jsxjj.base.BaseFragment;
import com.syj.jsxjj.config.Constant;
import com.syj.jsxjj.events.ChangeTabMainEvent;
import com.syj.jsxjj.events.FragmentRefreshEvent;
import com.syj.jsxjj.ui.authentication_new.activity.AuthenticationVerifityActivity;
import com.syj.jsxjj.ui.login.activity.ForgetPwdActivity;
import com.syj.jsxjj.ui.main.FragmentFactory;
import com.syj.jsxjj.ui.main.WebViewActivity;
import com.syj.jsxjj.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;

/**
 * Created by gyl on 2017/5/31 0031.
 */

public class DiscoverFragment extends BaseFragment {
    @BindView(R.id.web_view)
    WebView mWebView;
    @BindView(R.id.tv_tag_content)
    TextView mTvTagContent;
    @BindView(R.id.dialog_view)
    LinearLayout mDialogView;
    @BindView(R.id.progressbar)
    ProgressBar mProgressBar;
    @BindView(R.id.paddingView)
    View mPaddingView;

    public static DiscoverFragment fragment;
    private String mUrl = "";   //第一次loadUrl
    private String baseUrl = "";//切换账号后的url
    private String mtitle;//标题
    private int mAuthStep;
    private String mPhoneUrl;
    private String mZmxyUrl;

    public static DiscoverFragment getInstance() {
        if (fragment == null)
            fragment = new DiscoverFragment();
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_discover;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void loadData() {
        EventBus.getDefault().register(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            LinearLayout.LayoutParams paddingViewLayoutParams = (LinearLayout.LayoutParams) mPaddingView.getLayoutParams();
            paddingViewLayoutParams.height = Tool.getStatusBarHeight(getActivity());
            mPaddingView.setLayoutParams(paddingViewLayoutParams);
        }
        mTitle.setTitle(false, "");
        initView();
        mUrl = App.getConfig().DISCOVER;
        if (!TextUtils.isEmpty(mUrl)) {
            mUrl = getUrl(mUrl);
            mWebView.loadUrl(mUrl);

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FragmentRefreshEvent event) {
        if (event.getType() == UIBaseEvent.EVENT_LOGIN) {
            mUrl = baseUrl;
            baseUrl = App.getConfig().DISCOVER;
            if (!TextUtils.isEmpty(baseUrl)) {
                baseUrl = getUrl(baseUrl);
                mTitle.setTitle(false, mtitle);
                mWebView.loadUrl(baseUrl);
            }
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onReceiveEvent(AuthenticationCenterDataEvent event) {
//        if (event != null) {
//            mAuthStep = event.getAuthStep();
//            Log.i("mAuthStepMorefRAGMENT", event.getAuthStep() + "");
//            mPhoneUrl = event.getPhoneUrl();
//            mZmxyUrl = event.getZmxyUrl();
//        }
//    }

    private void initView() {
        mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDatabaseEnabled(true);
        //webview在安卓5.0之前默认允许其加载混合网络协议内容
        // 在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.addJavascriptInterface(new JavaMethod(), "nativeMethod");
    }

    public class JavaMethod {
        /**
         * 跳转到app的方法
         *
         * @param type json字符串
         *             {
         *             type:"0";
         *             }
         *             1：跳转到忘记登录密码
         *             2：跳转到忘记支付密码
         *             3：跳转到认证中心
         *             4：跳转到首页
         *             5：跳转到qq，并打开指定号码的客服聊天界面
         */
        @JavascriptInterface
        public void returnNativeMethod(String type, int authStep, String phoneUrl, String zmxyUrl) {
            Log.e("TAG", "type:" + type);
            if ("1".equals(type)) {
                Intent intent = new Intent(mContext, ForgetPwdActivity.class);
                intent.putExtra(Constant.CACHE_TAG_USERNAME, SpUtil.getString(Constant.CACHE_TAG_USERNAME));
                startActivity(intent);
            } else if ("2".equals(type)) {
                Intent intent = new Intent(mContext, ForgetPayPwdActivity.class);
                startActivity(intent);
            } else if ("3".equals(type)) {
                mAuthStep = authStep;
                mPhoneUrl = phoneUrl;
                mZmxyUrl = zmxyUrl;
                Intent intent = new Intent(mContext, AuthenticationVerifityActivity.class);
                intent.putExtra("authStep", mAuthStep);
                intent.putExtra("phoneUrl", mPhoneUrl);
                intent.putExtra("zmxyUrl", mZmxyUrl);
                startActivity(intent);
            } else if ("4".equals(type)) {
                EventBus.getDefault().post(new ChangeTabMainEvent(FragmentFactory.FragmentStatus.Lend));
            } else if ("5".equals(type)) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTitle.setRightTitle("咨询客服", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 这里只能为联系客服特殊处理，转到联系我们的页面
                                String qq_url = "mqqwpa://im/chat?chat_type=crm&uin=2152872885&version=1&src_type=web&web_src=file:://";//938009600
                                try {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qq_url)));
                                } catch (Exception e) {
                                    ToastUtil.showToast("请确认安装了QQ客户端");
                                }
                            }
                        });
                    }
                });

            }
        }
    }

    /**
     * 重新拼接url
     */
    public static String getUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        String ret_url = "";
        if (url.contains("?")) {
            ret_url = url + "&";
        } else {
            ret_url = url + "?";
        }
        ret_url += "clientType=android&appVersion="
                + ViewUtil.getAppVersion(App.getContext()) + "&deviceId="
                + ViewUtil.getDeviceId(App.getContext()) + "&mobilePhone=" +
                (App.getConfig().getLoginStatus() ? SpUtil.getString(Constant.CACHE_TAG_USERNAME) : "")
                + "&deviceName=" + ViewUtil.getDeviceName() + "&osVersion="
                + ViewUtil.getOsVersion() + "&appMarket="
                + App.getConfig().getChannelName() + "&appName=jsxjx";
        return ret_url.replace(" ", "");
    }

    class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();  // 接受所有网站的证书  解决https拦截问题
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mProgressBar.setVisibility(View.VISIBLE);

        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressBar.setVisibility(View.GONE);
            if (url.equals(mUrl)) {
                mWebView.clearHistory();
            }

            if (url.contains("credit-card/applyCard")) {
                mTitle.setTitle(false, "申请信用卡");
                mTitle.setRightTitle("办卡进度", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, WebViewActivity.class);
                        intent.putExtra("url", App.getConfig().CARDPROGRESS);
                        startActivity(intent);
                    }
                });
            }

            if (view.canGoBack()) {
                mTitle.setTitle(true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        view.goBack();
                    }
                }, view.getTitle());
            } else {
                mTitle.setTitle(false, view.getTitle());
                mTitle.setRightTitle("", null);
            }
        }
    }

    class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
        }

        @Override
        public void onReceivedTitle(final WebView view, String title) {
            super.onReceivedTitle(view, title);
            mtitle = title;//网页的标题
            mTitle.setTitle(false, mtitle);

            if (!baseUrl.equals(mUrl)) {//一级页面
                mTitle.setTitle(false, view.getTitle());
            }

            if (title.equals("申请信用卡")) {
                mTitle.setRightTitle("办卡进度", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, WebViewActivity.class);
                        intent.putExtra("url", App.getConfig().CARDPROGRESS);
                        startActivity(intent);
                    }
                });
            } else {
                mTitle.setTitle(false, title);
                mTitle.setRightTitle("", null);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
